package pers.hl.library.auth;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import pers.hl.library.common.Const;
import pers.hl.library.po.User;
import pers.hl.library.utils.ExceptionHelper;
import pers.hl.library.utils.SpringBeanTool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户角色控制拦截器，指定不同角色用户访问权限
 */
@Component
public class RoleInterceptor extends HandlerInterceptorAdapter {

    private static final List<String> adminUrls = new ArrayList<>();

    static {
        adminUrls.add("/lib/add");
        adminUrls.add("/lib/update");
        adminUrls.add("/lib/delete");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
//        LogUtils.i("服务器被请求，路径：" + uri);
        String applicationName = SpringBeanTool.getApplicationContext().getApplicationName();
        String url = uri.replace(applicationName, "");
//        LogUtils.i("替换项目名后的url："+url);
        User user = (User) request.getAttribute(Const.Keys.KEY_USER);
        if (user == null) {
            return true;
        }
        if (adminUrls.contains(url) && !user.isAdmin()) {
            ExceptionHelper.throw403("当前只有管理员可以操作");
        }
        return true;
    }
}
